package helper

import (
	"fmt"
	"go.uber.org/zap"
	"runtime"
)

func GoWithRecover(fn func(), logger *zap.Logger) {
	go func() {
		defer func() {
			if err := recover(); err != nil {
				if logger != nil {
					if rErr, ok := err.(runtime.Error); ok {
						logger.Error(fmt.Sprintf("recover runtime panic, err:%v", err), zap.Error(rErr))
					} else {
						logger.Error(fmt.Sprintf("recover custom panic, err:%v", err), zap.Any("error", err))
					}
				}
			}
		}()
		fn()
	}()
}

func WithRecover(fn func(), logger *zap.Logger) {
	defer func() {
		if err := recover(); err != nil {
			if logger != nil {
				if rErr, ok := err.(runtime.Error); ok {
					logger.Error(fmt.Sprintf("recover runtime panic, err:%v", err), zap.Error(rErr))
				} else {
					logger.Error(fmt.Sprintf("recover custom panic, err:%v", err), zap.Any("error", err))
				}
			}
		}
	}()
	fn()
}
